package OBJ;

import org.lwjgl.opengl.GL46;
import org.lwjgl.stb.STBImage;
import org.lwjgl.system.MemoryStack;

import java.nio.ByteBuffer;
import java.nio.IntBuffer;

// 纹理加载器
public class TextureLoader {
    public static int loadTexture(String path) {
        // 使用 MemoryStack 分配内存
        STBImage.stbi_set_flip_vertically_on_load(true);
        try (MemoryStack stack = MemoryStack.stackPush()) {
            IntBuffer width = stack.mallocInt(1);
            IntBuffer height = stack.mallocInt(1);
            IntBuffer channels = stack.mallocInt(1);

            // 加载图片数据
            ByteBuffer image = STBImage.stbi_load(path, width, height, channels, 4);
            if (image == null) {
                throw new RuntimeException("无法加载纹理: " + STBImage.stbi_failure_reason());
            }

            // 生成纹理 ID
            int textureId = GL46.glGenTextures();
            GL46.glBindTexture(GL46.GL_TEXTURE_2D, textureId);

            // 设置纹理参数
            GL46.glTexParameteri(GL46.GL_TEXTURE_2D, GL46.GL_TEXTURE_WRAP_S, GL46.GL_REPEAT); // 重复
            GL46.glTexParameteri(GL46.GL_TEXTURE_2D, GL46.GL_TEXTURE_WRAP_T, GL46.GL_REPEAT); // 重复
            GL46.glTexParameteri(GL46.GL_TEXTURE_2D, GL46.GL_TEXTURE_MIN_FILTER, GL46.GL_LINEAR); // 线性过滤
            GL46.glTexParameteri(GL46.GL_TEXTURE_2D, GL46.GL_TEXTURE_MAG_FILTER, GL46.GL_LINEAR); // 线性过滤

            // 上传纹理数据
            GL46.glTexImage2D(GL46.GL_TEXTURE_2D, 0, GL46.GL_RGBA,
                    width.get(), height.get(), 0,
                    GL46.GL_RGBA, GL46.GL_UNSIGNED_BYTE, image);
            GL46.glGenerateMipmap(GL46.GL_TEXTURE_2D);

            // 释放资源
            STBImage.stbi_image_free(image);
            return textureId;
        }
    }
}